package com.piggy.core.client;

import com.alibaba.fastjson2.JSONObject;
import com.piggy.core.common.AgreementConstant;
import com.piggy.core.model.HttpStatement;
import com.piggy.core.parser.ResponseParser;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.utils.SimpleReferenceCache;
import org.apache.dubbo.rpc.service.GenericService;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;

public class DubboClient {

    private final static Logger Logger = LoggerFactory.getLogger(DubboClient.class);

    public static void send(HttpStatement httpStatement, JSONObject jsonObject, Channel channel) {
        RegistryConfig registryConfig = new RegistryConfig();
        registryConfig.setAddress("zookeeper://59.110.50.234:2181?timeout=60000&blockUntilConnectedWait=60");

        ApplicationConfig applicationConfig = new ApplicationConfig();
        applicationConfig.setName(httpStatement.getApplicationName());
        applicationConfig.setQosEnable(false);

        ReferenceConfig<GenericService> referenceConfig = new ReferenceConfig<>();
        referenceConfig.setInterface(httpStatement.getInterfaceName());
        referenceConfig.setGeneric("true");
        referenceConfig.setAsync(false);
        referenceConfig.setTimeout(30000);

        ProtocolConfig protocolConfig = new ProtocolConfig();
        protocolConfig.setName("dubbo");
        protocolConfig.setPort(20888);

        DubboBootstrap bootstrap = DubboBootstrap.getInstance();
        DubboBootstrap dubboBootstrap = bootstrap.application(applicationConfig)
                .protocol(protocolConfig)
                .registry(registryConfig).start();

        dubboBootstrap.reference(referenceConfig);
        SimpleReferenceCache cache = SimpleReferenceCache.getCache();
        GenericService genericService = cache.get(referenceConfig);
        String parameterType = httpStatement.getIsExistParameter();
        Object[] objectArray = null;
        String[] typeArray = null;
        if(AgreementConstant.EXIST_PARAMETER.equals(parameterType)){
            objectArray = new Object[]{jsonObject};
            typeArray = new String[]{AgreementConstant.REQUEST_PARAMETER};
        }
        Object result = genericService.$invoke(httpStatement.getMethodName(), typeArray, objectArray);
        Logger.info("result -> {}", result);
        DefaultFullHttpResponse response = new ResponseParser().parse(result);
        channel.writeAndFlush(response);
    }

}
